import { reactive, toRefs, watch } from "vue"
import useMessage from './useMessage'
import { ElMessage } from "element-plus"
import { markAsVip } from "../api/guest"
import {
  setConversationNote,
  closeConversation,
  activeConversation,
  getConversations,
  assignConversation,
  assignAllConversation,
} from '../api/conversation'

export default () => {
  const state = reactive({
    loaded: false,
    currentConversation: {},
    currentListType: 'PROCESSING',
    pendingConversations: [], // 未处理的会话列表
    processingConversations: [], //  处理中的会话列表
  })

  //引入消息处理逻辑
  const message = useMessage()

  //判断是否是当前会话
  const isCurrentConversation = (conversationId) => {
    return Number(conversationId) === Number(state.currentConversation.id)
  }

  //清理当前会话的关联数据
  const flush = () => {
    const id = state.currentConversation.id
    let i = state.processingConversations.findIndex(item => item.id == id)
    if (i !== -1) {
      state.processingConversations.splice(i, 1)
    }
    state.currentConversation = {}
    //重置消息列表的参数信息
    message.reset()
  }

  //将会话状态从待处理更新会处理中
  const active = async () => {
    let result = await activeConversation(state.currentConversation.id)
    if (result.status === "success") {
      state.currentConversation.status = "PROCESSING"
      //将当前会话插入到我的列表中
      state.processingConversations.unshift(state.currentConversation)
    } else {
      ElMessage.error(result.message)
    }
  }

  //关闭当前会话
  const close = async () => {
    let result = await closeConversation(state.currentConversation.id)
    if (result.status === "success") {
      flush()
    } else {
      ElMessage.error(result.message)
    }
  }

  //指派当前会话给某个人
  const assign = (uid) => {
    assignConversation(state.currentConversation.id, uid).then(result => {
      if (result.status === 'success') {
        flush()
        ElMessage.success("指派成功")
      } else {
        ElMessage.error(result.message)
      }
    })
  }

  //指派当前会话给某个人
  const assignAll = (from_uid, to_uid) => {
    assignAllConversation(from_uid, to_uid).then(result => {
      if (result.status === 'success') {
        ElMessage.success("指派成功")
        window.location.reload()
      } else {
        ElMessage.error(result.message)
      }
    })
  }

  //选中会话
  const selection = (conversation) => {
    if (!isCurrentConversation(conversation.id)) {
      state.currentConversation = conversation
      //将未读消息数置为0
      state.currentConversation.user_unread = 0
      //获取消息列表
      message.getMsgList(conversation.id, false)
    }
  }

  //设置会话的备注信息
  const comment = async () => {
    let content = state.currentConversation.note.trim()
    if (content) {
      let result = await setConversationNote(state.currentConversation.id, content)
      if (result.status != 'success') {
        ElMessage.error(result.message)
      }
    }
  }

  //根据给定的类型获取会话列表
  const loadConversations = async (type) => {
    //待处理的会话列表需要每次都重新获取,因为会有新的会话进来,我们需要列表数据及时刷新
    if (type === "PENDING") {
      let result = await getConversations("PENDING")
      state.pendingConversations = result.data
    }
    //正在处理的会话列表不需每次都重新获取,所以有如下判断
    if (type === "PROCESSING" && !state.loaded) {
      let result = await getConversations("PROCESSING")
      state.processingConversations = result.data
      state.loaded = true
    }
  }

  //设置会话最新消息
  const setLatestMsg = (conversationId, lateMsg, hasRead = true) => {
    if (isCurrentConversation(conversationId)) {
      state.currentConversation.late_msg = lateMsg
      //插入消息到消息列表
      message.addMsg(lateMsg)
    } else {
      let dest = state.processingConversations.find(item => item.id == conversationId)
      if (dest) {
        dest.late_msg = lateMsg
        if (!hasRead) {
          dest.user_unread++
        }
      }
    }
  }

  //设置为VIP
  const setVip = async () => {
    let result = await markAsVip(state.currentConversation.guest_id)
    if (result.status == "success") {
      state.currentConversation.guest.vip = !state.currentConversation.guest.vip
    } else {
      ElMessage.error("设置失败")
    }
  }

  return {
    ...toRefs(state),
    ...message,
    assign,
    assignAll,
    active,
    close,
    comment,
    selection,
    setVip,
    setLatestMsg,
    loadConversations,
    isCurrentConversation,
  }
}
